package com.xuxu.blog.controller.loginAndregister;

import com.xuxu.blog.entity.UserEntity;
import com.xuxu.blog.service.UserService;
import com.xuxu.blog.service.loginAndregister.MessageService;
import com.xuxu.blog.utils.MD5Utils;
import com.xuxu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @className: LoginController
 * @author: Maxuxu
 * @date: 2022/8/22 10:01
 * @description: 登陆验证的控制类
 */
@RestController
@Slf4j
@RequestMapping("/blog")
public class LoginByMobileController {
    @Autowired
    MessageService messageService;
    @Autowired
    UserService userService;

    /**
     * 手机号免密登录（如果没有注册过-新用户的话就会自动注册）
     *
     * @return
     */
    @RequestMapping("/user/loginMobile")
    public R LoginByPhone(@RequestBody Map<String,String> form) {
        log.error("传入的表单数据是：{}", form);
        String phone = form.get("username");
        String code = form.get("code");
        int verifyCode = messageService.verifyCode(phone,code);
        log.error("reids验证的结果是：{}", verifyCode);
        if (verifyCode == 1) {
           return userService.LoginByPhone(phone);
        } else if (verifyCode == 0) {
            return R.error("验证码错误");
        }else {
            return R.error("验证码失效，请重新发送");
        }
    }

    /**
     * 向指定用户发送短信验证码
     * @param phone
     * @param code
     * @return
     * @throws Exception
     */
    @PostMapping("/user/sendSms/{username}")
    public R SendCode(@PathVariable("username") String phone,String code) throws Exception {
        boolean msg = messageService.verifyCount(phone);
        if (msg) {
            return R.ok("发送成功");
        }
        return R.error("30分钟只能发送3次");
    }
}
